<?php

declare(strict_types=1);

namespace App\Http\Controllers\Manage;

use App\Repositories\Manage\MemberRepository;
use App\Repositories\ParkRepository;
use Exception;

class MemberController extends ManageBaseController
{
    private $memberRep = NULL;

    public function __construct(
        MemberRepository $memberRep
    )
    {
        parent::__construct();
        $this->memberRep = $memberRep;
    }

    public function index()
    {
        $filter = request()->all();
        $res = $this->memberRep->getList($filter, $this->pageNum, $this->pageSize);
        return retSuc($res);
    }

    public function update($id = null)
    {
        $data = request()->all();
        if (!intval($id))
            return retFail("参数错误");

        $member = $this->memberRep->getOne($id);
        if (empty($member))
            return retFail("会员不存在");

        $last_id = $this->memberRep->saveOrUpdate([
            'gender' => $data['gender'],
            'username' => $data['username'] ?? '',
            'mobile' => $data['mobile'] ?? '',
            'summary' => $data['summary'] ?? '',
            'is_deliver' => $data['is_deliver'] ?? 2,
            'is_pick' => $data['is_pick'] ?? 0,
            'is_replace_order' => $data['is_replace_order'] ?? 2,
        ], $id ?? 0);

        if (!$last_id) {
            return retFail("更新失败");
        }

        try {
            $types = $data['type'] ?? [];
            $this->memberRep->updateType(intval($last_id), $types);


            //会员关注园区
            (new ParkRepository())->updateMemberMapping(intval($last_id ?? 0), $data['is_deliver'] == 1 ? $data['park_id'] : []);
            $res = $this->memberRep->getOne($last_id);

            return retSuc($res);
        } catch (Exception $e) {
            return retFail($e->getMessage());
        }
    }

    public function detail($id = 0)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");

        $res = $this->memberRep->getOne($id);

        return retSuc($res);
    }

    public function delete($id)
    {
        $id = intval($id);
        if (empty($id)) {
            return retFail("参数错误");
        }

        return $this->memberRep->batchDelete($id);
    }

    /**
     * 增加积分
     */
    public function update_integral()
    {
        $data = request()->all();
//        $integral = intval($data['integral']);
        if (empty($data['id'])) {
            return retFail("参数错误");
        }

        $data['uid'] = UID;

        return $this->memberRep->updateIntegral($data);
    }

}
